package com.justnow.offer;


import java.util.ArrayList;
import java.util.List;

/**
 * @author justnow
 * Created on 2020-08-30
 * Description
 *
 * 输入一个整数数组，实现一个函数来调整该数组中数字的顺序，使得所有的奇数位于数组的前半部分，
 * 所有的偶数位于数组的后半部分，并保证奇数和奇数、偶数和偶数之间的相对位置不变。
 */
public class Solution1 {

    public int[] reOrderArray (int[] array) {
        // write code here
        int head = 0, tail = array.length - 1;

        while (head < tail) {
            while (array[head] % 2 != 0 && head < tail) {
                head++;
            }
            while (array[tail] % 2 == 0 && head < tail) {
                tail--;
            }

            int temp = array[head];

            array[head] = array[tail];

            array[tail] = temp;
        }
        return array;
    }

    public int[] reOrderArray2 (int[] array) {
        List<Integer> list1 = new ArrayList<>(); //存偶数
        List<Integer> list2 = new ArrayList<>(); //存奇数
        List<Integer> list = new ArrayList<>();
        int[] result = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            if (array[i] % 2 == 0)
                list1.add(array[i]);
            else
                list2.add(array[i]);
        }

        for (Integer integer : list2) {
            list.add(integer);
        }

        for (Integer integer : list1) {
            list.add(integer);
        }


        for (int i = 0; i < list2.size(); i++) {
            result[i] = list2.get(i);
        }
        int size = list2.size();
        for (int j = 0; j < list1.size(); j++) {
            result[j + size] = list1.get(j);
        }

        return result;
    }


    public static void main(String[] args) {
        int[] array = {1, 4, 9, 12, 7};
        Solution1 solution1 = new Solution1();
        int[] ints = solution1.reOrderArray2(array);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }
}
